package com.xiaolin.service;

import com.github.pagehelper.PageHelper;
import com.xiaolin.dao.UserMapper;
import com.xiaolin.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author XiaoLin
 * @date 2019/2/22 20:44
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 通过Id查询用户信息
     *
     * @param userId
     * @return
     */
    public User findUserById(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 登陆
     *
     * @param user
     * @return
     */
    public User login(User user) throws Exception {
        User u = userMapper.loginName(user);
        if (u != null) {
            return u;
        }
        u = userMapper.loginPhone(user);

        return u;
    }

    /**
     * 查询用户头像信息
     *
     * @param uname
     * @return
     */
    public String findUimage(String uname) {
        Example e = new Example(User.class);
        Example.Criteria criteria = e.createCriteria();
        criteria.andEqualTo("username", uname);
        criteria.orEqualTo("phone", uname);
        List<User> userList = userMapper.selectByExample(e);
        if (userList.size() == 0) {
            return null;
        }
        return userList.get(0).getUimage();
    }

    /**
     * 获取推荐用户
     *
     * @return
     */
    public List<User> getRecoList(Integer page, Integer size, String username, String uid) {
        //TODO 可以根据年龄,爱好,兴趣,地区进行推荐
        PageHelper.startPage(page, size);
        return userMapper.findRecoUser(username, "%" + username + "%", uid);
    }

    /**
     * 保存用户
     *
     * @param user
     */
    public void insert(User user) {
        userMapper.insert(user);
    }

    public boolean existsName(String username) {
        Example e = new Example(User.class);
        Example.Criteria criteria = e.createCriteria();
        criteria.andEqualTo("username", username);
        List<User> userList = userMapper.selectByExample(e);
        return userList.size() > 0;
    }

    public void updata(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    public User findUserInfo(String uid) {
        return userMapper.selectFriendById(uid);
    }
}
